import { topCategory } from '@/api/constants'
import { findAllCategory } from '@/api/home'
import type { IRootState } from '@/store/types'
import type { CategoryList, ICategoryItem } from '@/types/api/home'
import type { Module } from 'vuex'
import type { ICategory } from './types'

const categoryModule: Module<ICategory, IRootState> = {
  namespaced: true,
  state: () => ({
    // 分类导航数据，topCategory 为默认数据，如果没有默认数据，页面加载的时候会空白
    list: topCategory.map((item) => ({ name: item })) as CategoryList
  }),
  mutations: {
    // 修改分类导航数据数据
    setList(state, newList) {
      state.list = newList
    },

    // 修改当前一级分类下的open数据为true
    show(state, item) {
      const category = state.list.find((category) => category.id === item.id)
      category!.open = true
    },

    // 修改当前一级分类下的open数据为false
    hide(state, item) {
      const category = state.list.find((category) => category.id === item.id)
      category!.open = false
    }
  },
  actions: {
    // 获取分类导航数据数据
    async getList(context) {
      const res = await findAllCategory()
      // 给一级分类添加 open 属性，用来控制二级分类显示隐藏的数据
      res.data.result.forEach((item) => {
        item.open = false
      })
      context.commit('setList', res.data.result)
    }
  }
}

export default categoryModule
